package edu.nf.supermarket.service.impl.pay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.ExtUserInfo;
import com.alipay.api.domain.ExtendParams;
import com.alipay.api.domain.GoodsDetail;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import edu.nf.supermarket.consts.AlipayConfigEnum;
import edu.nf.supermarket.exception.PayException;
import edu.nf.supermarket.service.pay.AlipayService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yjj
 * @date 2025-05-21
 */
@Service("alipayService")
public class AlipayServiceImpl implements AlipayService {
    private final AlipayClient alipayClient;

    public AlipayServiceImpl(AlipayClient alipayClient) {
        this.alipayClient = alipayClient;
    }


    /**
     * 创建订单
     *
     * @param orderNo 订单编号
     * @param amount  订单金额
     * @return 支付宝支付页面
     */
    @Override
    public String createWebOrder(String orderNo, String amount, String subject, Map<String, Object> extraParams) throws PayException, AlipayApiException {
        // 构建请求对象
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        // 设置异步通知地址（后台回调）
        request.setNotifyUrl(AlipayConfigEnum.getInstance().getNotifyUrl());
        request.setReturnUrl(AlipayConfigEnum.getInstance().getReturnUrl());

        // 构建支付模型
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(orderNo);              // 商户订单号
        model.setTotalAmount(amount);               // 订单总金额
        model.setSubject(subject);                  // 商品描述
        model.setProductCode("FAST_INSTANT_TRADE_PAY"); // 产品码

        // 可选参数设置
        if (extraParams != null) {
            if (extraParams.containsKey("goodsDetail")) {
                model.setGoodsDetail((List<GoodsDetail>) extraParams.get("goodsDetail"));
            }
            //超时支付设置
            if (extraParams.containsKey("timeExpire")) {
                model.setTimeExpire((String) extraParams.get("timeExpire"));
            }
            if (extraParams.containsKey("storeId")) {
                model.setStoreId((String) extraParams.get("storeId"));
            }
            if (extraParams.containsKey("extendParams")) {
                model.setExtendParams((ExtendParams) extraParams.get("extendParams"));
            }
            if (extraParams.containsKey("extUserInfo")) {
                model.setExtUserInfo((ExtUserInfo) extraParams.get("extUserInfo"));
            }
        }

        request.setBizModel(model);

        // 执行请求
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");

        // 日志输出
        System.err.println("支付宝返回错误码：" + response.getCode());
        System.err.println("错误描述：" + response.getMsg());
        System.err.println("子错误码：" + response.getSubCode());
        System.err.println("子错误描述：" + response.getSubMsg());
        System.out.println("响应内容：" + response.getBody());
        if (response.isSuccess()) {
            return response.getBody(); // 返回 HTML 表单内容，前端可直接渲染跳转
        } else {
            throw new PayException(Integer.parseInt(response.getSubCode()), response.getSubMsg());
        }
    }
}
